<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useUserStore } from '@/stores'
import { useGetDeletedTasksService, useDeleteTaskCompletelyService, useDeleteAllSecondlyDeletedTasksService } from '@/api/task'

// 控制一键删除弹出框显隐
const visible = ref(false)
// 定义组件emit
const emit = defineEmits(['refreshTasks'])
// 父组件传来的已删除任务列表
const props = defineProps({
  taskList: {
    type: Array,
    default: () => []
  }
})
const userStore = useUserStore()
// 用户id
const user_id = userStore.userId
// 已删除任务列表
const deletedTasksList = ref(props.taskList)
// 未完成任务列表
const toFinishList = ref(deletedTasksList.value.filter(item => !item.isFinished))
// 已完成任务列表
const finishedList = ref(deletedTasksList.value.filter(item => item.isFinished))
// 未完成任务数量
const toFinishCount = computed(() => toFinishList.value.length || 0)
// 已完成任务数量
const finishedCount = computed(() => finishedList.value.length || 0)
// 删除任务事件
const deleteTaskCompletely = async (id) => {
  const res = await useDeleteTaskCompletelyService({ id })
  if(res.data.status === 0) {
    ElMessage.success('任务删除成功！')
  } else {
    ElMessage.error('任务删除失败！')
  }
  // 前端立即更新任务列表，防止后端响应时间长
  deletedTasksList.value = deletedTasksList.value.filter(item => item.id !== id)
  // 提醒父组件刷新任务列表(包括TodayTasks、SevenDaysTask、AllTask、OtherTask、DeletedTask、FinishedTask)
  emit('refreshTasks')
  console.log('删除后deletedTasksList.value：' + JSON.stringify(deletedTasksList.value))
}
// 一键删除所有任务事件
const deleteAllTasks = async () => {
  visible.value = false
  const res = await useDeleteAllSecondlyDeletedTasksService({ user_id })
  if (res.data.status === 0) {
    ElMessage.success('任务删除成功！')
  } else {
    ElMessage.error('任务删除失败！')
  }
  // 前端立即更新任务列表，防止后端响应时间长
  deletedTasksList.value = []
  // 提醒父组件刷新任务列表
  emit('refreshTasks')
  console.log('删除后deletedTasksList.value：' + JSON.stringify(deletedTasksList.value))
}
// 拖动开始
const dragstart = (index, event) => {
  event.dataTransfer.setData("text", index)
  console.log("您已成功拖动元素" + index)    
}
// 进行放置
const drop = (targetIndex, list, event) => {
  const draggedIndex = parseInt(event.dataTransfer.getData("text"), 10); // 转换为整数
  const draggedTask = list[draggedIndex]; // 获取拖拽的任务
  list.splice(draggedIndex, 1); // 先移除原位置的元素
  list.splice(targetIndex, 0, draggedTask); // 在新位置插入
  console.log("drop", event)
  console.log('targetIndex:' + targetIndex + '.')
  console.log('draggedIndex:' + draggedIndex + '.')
  console.log(list)
}
// 放置位置 - 阻止默认事件,即允许放置
const dragover = (event) => {
  event.preventDefault()
}

// 监听父组件传来的已删除任务列表
watch(
  () => props.taskList,
  (newVal) => {
    deletedTasksList.value = newVal
  }
)
// 监听列表变化，实时修改数量
watch(
  [deletedTasksList],
  () => {
    console.log('列表发生变化了')  
    toFinishList.value = deletedTasksList.value.filter(item => !item.isFinished)
    finishedList.value = deletedTasksList.value.filter(item => item.isFinished)
  },
  {
    deep: true
  }
)
</script>

<template>
  <div class="list">
    <!-- 顶部 -->
    <div class="list-header">
      <div class="left">
        <div class="iconfont">&#xe790;</div>
        <div class="header-title">垃圾桶</div>
      </div>
      <!-- 一键删除按钮 -->
      <div class="right">
        <el-popover :visible="visible" placement="top" :width="180">
          <p>你确定要一键删除所有任务吗?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="small" text @click="visible = false">取消</el-button>
            <el-button size="small" type="primary" @click="deleteAllTasks">
              确认
            </el-button>
          </div>
          <template #reference>
            <div @click="visible = true" class="iconfont">&#xe60c;</div>
          </template>
        </el-popover>
      </div>
    </div>
    <!-- 任务部分 -->
    <div class="tasks">
      <!-- 未完成 -->
      <div class="toFinish">
        <div class="section-header">
          <span class="iconfont">&#xe649;</span>
          <div class="title">未完成</div>
          <span class="count">{{ toFinishCount }}</span>
        </div>
        <!-- 任务列表 -->
        <div class="tasksList">
          <ul>
            <li draggable="true" 
            @dragstart="dragstart(index, $event)"
            @drop.prevent="drop(index, toFinishList, $event)"
            @dragover.prevent="dragover"
            v-for="(item, index) in toFinishList" 
            :key="item.id"
            >
              <div class="task">
                <!-- 拖动排序按钮 -->
                <SortBtn class="drag-handle"></SortBtn>
                <div class="iconfont">&#xe642;</div>
                <div class="text">{{ item.title }}</div>
              </div>
              <div class="icon">
                <div class="classify">{{ item.classify_name }}</div>
                <div class="date">{{ item.finish_date }}</div>
                <!-- 删除按钮 -->
                <DeleteTaskBtn @delete-click="() => deleteTaskCompletely(item.id)"/>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <!-- 已完成 -->
      <div class="finished">
        <div class="section-header">
          <span class="iconfont">&#xe649;</span>
          <div class="title">已完成</div>
          <span class="count">{{ finishedCount }}</span>
        </div>
        <!-- 任务列表 -->
        <div class="tasksList">
          <ul>
            <li draggable="true" 
            @dragstart="dragstart(index, $event)" 
            @drop.prevent="drop(index, finishedList, $event)" 
            @dragover.prevent="dragover"  
            v-for="(item, index) in finishedList" 
            :key="item.id"
            >
              <div class="task">
                <SortBtn></SortBtn>
                <div class="iconfont">&#xe79e;</div>
                <div class="text">{{ item.title }}</div>
              </div>
              <div class="icon">
                <div class="classify">{{ item.classify_name }}</div>
                <div class="date">{{ item.finish_date }}</div>
                <!-- 父传子传给子组件来删除任务 -->
                <DeleteTaskBtn @delete-click="() => deleteTaskCompletely(item.id)"/>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.list {
  height: 100vh;
  display: flex;
  padding-bottom: 30px;
  flex-direction: column;
  border-right: 1px solid #ccc;
  overflow: auto;

  .list-header {
    margin: 20px;
    height: 40px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .left,
    .right {
      display: flex;
      align-items: center;

      .iconfont {
        margin-right: 10px;
        font-size: 23px;
        color: #a3a3a3;
        cursor: pointer;
      }

      .header-title {
        font-size: 22px;
        font-weight: 700;
      }
    }
  }

  .tasks {
    overflow: auto;

    .toFinish,
    .finished {
      margin: 0 20px;
      
      .section-header {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #a3a3a3;

        .title {
          margin: 0 5px;
          color: #000;
          font-weight: 700;
        }
      }
      
      .tasksList {
        ul li {
          height: 40px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 10px 0;
          padding: 0 15px 0 0;

          .task {
            display: flex;
            align-items: center;

            .iconfont {
              margin: 0 8px;
              color: #a3a3a3;
              font-size: 20px;
            }

            .text {
              font-size: 14px;
              color: #a3a3a3;
            }
          }

          .icon {
            display: flex;
            align-items: center;

            .classify,
            .date {
              margin-right: 5px;
              font-size: 12px;
              color: #a3a3a3;
            }

            // 使用scoped时，无法修改子组件的样式，使用::v-deep则可以1修改子组件样式
            ::v-deep(.iconfont) {
              color: #a3a3a3;
              font-size: 14px;
            }
          }
        }

        ul li:hover {
          border-radius: 5px;
          background-color: #f1f1f1;
        }
      }
    }
  }
}

// 超小屏幕下
@media screen and (max-width: 575px) {
  .list {
    width: 100%;
  }
}

// 小屏幕下
@media screen and (min-width: 576px) {
  .list {
    width: 81%;
  }
}

// 中等、大、超大屏幕下
@media screen and (min-width: 768px) {
  .list {
    width: 40%;
  }
}

</style>
